package com.dfiles.utils;

import java.lang.reflect.Field;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.dfiles.R;

public class UIHelper {

	private static Toast toast = null;

	public static final int DIRECTION_NEXT = 101;
	public static final int DIRECTION_PREVIOUS = 201;

	/**
	 * 跳转到指定num的view
	 * 
	 * @param context
	 * @param flipper
	 * @param num
	 *            -
	 */
	public static void flipNum(Context context, ViewFlipper flipper, int direction, int num) {
		if (direction == DIRECTION_NEXT) {
			flipper.setInAnimation(context, R.anim.flipper_right_in);
			flipper.setOutAnimation(context, R.anim.flipper_left_out);
		} else if (direction == DIRECTION_PREVIOUS) {
			flipper.setInAnimation(context, R.anim.flipper_left_in);
			flipper.setOutAnimation(context, R.anim.flipper_right_out);
		}
		flipper.setDisplayedChild(num);
	}

	/**
	 * 设置为全屏模式，即隐藏标题栏和系统操作栏
	 */
	public static void setFullScreen(Activity activity) {
		// Window window = activity.getWindow();
		// 隐藏标题栏
		activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 隐藏操作栏
		// activity.getWindow().getDecorView().setSystemUiVisibility(View.GONE);
		// 隐藏4.2顶部的状态栏
		activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// // Hide status bar
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// // Show status bar
		// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	/**
	 * 隐藏/显示 系统操作栏
	 */
	public static void toogleSystemBar(Activity activity) {
		Window window = activity.getWindow();
		if (View.GONE == window.getDecorView().getSystemUiVisibility()) {
			window.getDecorView().setSystemUiVisibility(View.VISIBLE);
		} else {
			window.getDecorView().setSystemUiVisibility(View.GONE);
		}
	}

	/**
	 * 隐藏和显示view
	 * 
	 * @param view
	 * @param space
	 *            is still takes up space for layout purposes
	 */
	public static void toogleVisibility(View view, boolean space) {
		if (view.getVisibility() == View.VISIBLE) {
			if (space) {
				view.setVisibility(View.INVISIBLE);
			} else {
				view.setVisibility(View.GONE);
			}

		} else {
			view.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * Toast提示消息
	 * 
	 * @param context
	 * @param text
	 * @param isShort
	 *            LENGTH_SHORT
	 */
	public static void makeToast(Context context, CharSequence text, boolean isShort) {
		int duration = isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
		// Toast.makeText(context, text, duration).show();
		if (toast == null) {
			toast = Toast.makeText(context, text, duration);
		} else {
			toast.setText(text);
			toast.setDuration(duration);
		}
		toast.show();

	}

	public static void makeToast(Context context, CharSequence text) {
		// Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
		if (toast == null) {
			toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	/**
	 * Toast提示消息
	 * 
	 * @param context
	 * @param resId
	 * @param isShort
	 *            LENGTH_SHORT
	 */
	public static void makeToast(Context context, int resId, boolean isShort) {
		int duration = isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
		/*
		 * int duration = isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
		 * 
		 * Toast.makeText(context, resId, duration).show();
		 */
		if (toast == null) {
			toast = Toast.makeText(context, resId, duration);
		} else {
			toast.setText(resId);
			toast.setDuration(duration);
		}
		toast.show();
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return (int) (dpValue * metrics.density + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return (int) (pxValue / metrics.density + 0.5f);
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	/** 获取屏幕宽 */
	public static int getDisplayWidth(Activity activity) {
		final DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);// 获取分辨率
		return metric.widthPixels;
	}

	/**
	 * 获取屏幕高 px
	 */
	public static int getDisplayHeight(Context context) {
		DisplayMetrics metric = context.getResources().getDisplayMetrics();// 获取分辨率
		return metric.heightPixels;
	}

	/**
	 * 获取屏幕高 px
	 */
	public static int getDisplayWidth(Context context) {
		DisplayMetrics metric = context.getResources().getDisplayMetrics();// 获取分辨率
		return metric.widthPixels;
	}

	/**
	 * @author Tim 获取屏幕高
	 */
	public static int getDisplayHeight(Activity activity) {
		final DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);// 获取分辨率
		return metric.heightPixels;
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param activity
	 */
	public static void hideSoftInputFromWindow(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param view
	 */
	public static void hideSoftInputFromWindow(View view) {
		InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 显示键盘
	 * 
	 * @param context
	 * @param view
	 */
	public static void showInputMethodFromView(Context context, View view) {
		InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		im.showSoftInput(view, 0);
	}

	public static void keepDialog(DialogInterface dialog) {
		try {
			Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
			field.setAccessible(true);
			field.set(dialog, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void distoryDialog(DialogInterface dialog) {
		try {
			Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
			field.setAccessible(true);
			field.set(dialog, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分享文本信息
	 * 
	 * @param title
	 * @param value
	 */
	public static void shareText(Context context, String title, String value) {
		Intent sendIntent = new Intent();
		sendIntent.setAction(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_TEXT, value);
		// sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		sendIntent.setType("text/plain");
		context.startActivity(Intent.createChooser(sendIntent, title));
	}

	/**
	 * 
	 * @Description: 调用浏览器打开url
	 * @param context
	 * @param uriString
	 * @return void
	 * @throws
	 */
	public static void openExplorer(Context context, String uriString) {
		Uri uri = Uri.parse(uriString);
		context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
	}

	private Runnable runnable;

	public void setButtonDrawableCenter(final Context context, final Button button, final int imageID, final int spacing) {
		final Handler handler = new Handler();
		runnable = new Runnable() {
			@Override
			public void run() {
				if (button.getMeasuredWidth() == 0) {
					handler.postDelayed(runnable, 0);
				} else {
					Drawable drawable = context.getResources().getDrawable(imageID);
					button.measure(0, 0);
					int width = button.getMeasuredWidth();
					// int height = button.getMeasuredHeight();

					Rect bounds = new Rect();
					Paint textPaint = button.getPaint();
					textPaint.getTextBounds(button.getText().toString(), 0, button.getText().length(), bounds);
					// int txt_height = bounds.height();
					int txt_width = bounds.width();

					int img_width = drawable.getIntrinsicWidth();
					// int img_height = drawable.getIntrinsicHeight();
					// int content_height = txt_height + img_height + spacing;
					int content_width = txt_width + img_width + spacing;

					int padding_w = 0;
					if (width >= content_width)
						padding_w = width / 2 - content_width / 2;
					// int padding_h = height / 2 - content_height / 2;

					// button.setCompoundDrawablesWithIntrinsicBounds(drawable,
					// null, null, null);
					button.setPadding(padding_w, 0, 0, 0);
					button.setCompoundDrawablePadding(-padding_w);
				}
			}
		};
		handler.postDelayed(runnable, 0);
	}

	/**
	 * 显示提示消息对话框窗口
	 * 
	 * @param ctx
	 * @param msg
	 * @param listener
	 */
	public static void msgUIShowDialog(Context ctx, String msg, DialogInterface.OnClickListener listener) {
		AlertDialog dialog = new AlertDialog.Builder(ctx).create();
		dialog.setTitle(ctx.getResources().getString(R.string.msg_title));
		dialog.setMessage(msg);
		dialog.setCancelable(false);
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, ctx.getResources().getString(R.string.sure), listener);
		dialog.show();
	}

	/**
	 * 
	 * @Description: 圆角图片
	 * @param bitmap
	 * @return Bitmap
	 * @throws
	 */
	public static Bitmap toOvalBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getWidth(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		Paint paint = new Paint();
		Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		RectF rectF = new RectF(rect);

		canvas.drawOval(rectF, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rectF, paint);
		return output;
	}

	public static void dismissDialog(ProgressDialog progressDialog) {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.cancel();
			progressDialog = null;
		}
	}

	/**
	 * force to show overflow menu in actionbar for android 4.4 below
	 * 
	 * @param context
	 */
	public static void getOverflowMenu(Context context) {
		try {
			ViewConfiguration config = ViewConfiguration.get(context);
			Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 提示TextView
	 * 
	 * @param tv_alert
	 * @param msg
	 * @param isOk
	 */
	public static void showAlertText(Context ctx, TextView tv_alert, String msg, boolean isOk) {
		tv_alert.setText(msg);
		if (isOk) {
			tv_alert.setTextColor(ctx.getResources().getColor(R.color.green));
		} else {
			tv_alert.setTextColor(ctx.getResources().getColor(R.color.red));
		}
	}

	/**
	 * 获取当前分辨率下指定单位对应的像素大小（根据设备信息） px,dip,sp -> px
	 * 
	 * Paint.setTextSize()单位为px
	 * 
	 * 代码摘自：TextView.setTextSize()
	 * 
	 * @param unit
	 *            TypedValue.COMPLEX_UNIT_*
	 * @param size
	 * @return
	 */
	public static float getRawSize(Context context, int unit, float size) {
		Resources r;

		if (context == null)
			r = Resources.getSystem();
		else
			r = context.getResources();

		return TypedValue.applyDimension(unit, size, r.getDisplayMetrics());
	}

	public static void startOtherApp(Context ctx, String packageName) {
		// 这个是另外一个应用程序的包名， 这个参数是要启动的Activity
		try {
			Intent launchIntent = ctx.getPackageManager().getLaunchIntentForPackage(packageName);
			if (null != launchIntent) {
				launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				ctx.startActivity(launchIntent);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static long lastClickTime;

	/**
	 * 是否快速点击
	 * 
	 * @return
	 */
	public static boolean isFastDoubleClick() {
		long curTime = System.currentTimeMillis();
		long timeD = curTime - lastClickTime;
		if (0 < timeD && timeD < 1000) {
			return true;
		}
		lastClickTime = curTime;
		return false;
	}

	/**
	 * 
	 * @Description: 获取选中和非选中的背景色
	 * @param context
	 * @param selected
	 * @return int
	 * @throws
	 */
	public static int toggleSelectedRes(Context context, boolean selected) {
		int res = R.color.full_transparent;
		if (selected) {
			res = R.drawable.shape_selected;
		} else {
			res = R.color.full_transparent;
		}
		return res;
	}
}
